<!-- eslint-disable max-len -->
<template>
  <div class="search min-h-screen from-hex-FFFFFF to-hex-F5F5F5 bg-gradient-to-b" :style="{ paddingTop: `${topHight}px` }">
    <uni-nav-bar title="搜索" left-icon="left" :border="false" @clickLeft="goback" />
    <div class="p-38rpx">
      <div class="flex">
        <div class="mb-32rpx flex-1">
          <uni-search-bar v-model.trim="searchValue" radius="100" bg-color="#f5f5f5" :focus="true" @cancel="cancelSearch" @confirm="onSearch">
            <template #searchIcon>
              <image
                :src="`${cdnUrl}/svgicons/search/search.svg${imgVersion}`"
                mode="scaleToFill"
                class="h-40rpx w-40rpx"
              />
            </template>
          </uni-search-bar>
        </div>
      </div>
      <!--  历史记录 -->
      <div>
        <div class="flex">
          <span class="flex-1 text-28rpx">历史记录</span>
          <span @click="delHistory"> <image
            :src="`${cdnUrl}/svgicons/search/del.svg${imgVersion}`"
            mode="scaleToFill"
            class="h-40rpx w-40rpx"
          /></span>
        </div>
        <div class="history-item">
          <div v-if="searchStore.teaSearchHistoryList.length>0">
            <div v-for="item in searchStore.teaSearchHistoryList" :key="item" class="mr-32rpx mt-32rpx inline-block h-50rpx border-1 border-hex-f2f2f2 rounded-30rpx border-solid pl-20rpx pr-20rpx text-24rpx leading-50rpx" @click="heldHistory(item)">{{ item }}</div>
          </div>
          <div v-else class="text-24rpx text-hex-999" style="text-align: center;">暂无数据</div>
        </div>
      </div>
      <!--  热门推荐 -->
      <div class="mt-52rpx">
        <div class="flex">
          <span class="flex-1 text-28rpx">热门推荐</span>
          <span @click="heldeRefresh"><image
            :src="`${cdnUrl}/svgicons/search/refresh.svg${imgVersion}`"
            mode="scaleToFill"
            class="h-40rpx w-40rpx"
          /></span>
        </div>
        <div v-if="hotSearchList.length>0">
          <div v-for="item in hotSearchList" :key="item" class="mr-32rpx mt-32rpx inline-block h-50rpx border-1 border-hex-f2f2f2 rounded-30rpx border-solid pl-20rpx pr-20rpx text-24rpx leading-50rpx">{{ item.hotName }}</div>
        </div>
        <div v-else class="text-24rpx text-hex-999" style="text-align: center;">暂无数据</div>
      </div>

      <!-- 热榜排行 -->
      <div class="mt-52rpx">
        <swiper v-if="hotShopList.length>0" class="swiper-container h-670rpx w-100%" :current="currentIndex" @change="swiperChange">
          <swiper-item v-for="(item, index) in hotShopList" :key="index" class="relative rounded-32rpx bg-hex-ffffff shadow">
            <image
              :src="`${cdnUrl}/imgs/detail/bg.png${imgVersion}`"
              class="absolute left-0 right-0 top-0 z--1 w-100%"
              mode="widthFix"
            />
            <div class="item relative h-100% w-100% rounded-20rpx p-24rpx shadow-sm">
              <span class="title text-28rpx">
                <image
                  :src="`${cdnUrl}/svgicons/search/emoji.svg${imgVersion}`"
                  mode="scaleToFill"
                  class="h-28rpx w-28rpx"
                />
                <span>{{ item.recommendName }}</span>
              </span>

              <div v-for="(hot, i) in item.commendProductList" :key="hot.id" class="hot-item mt-46rpx h-90rpx flex pr-25rpx" @click="goDetail(hot.unionFlag, hot.productId)">
                <div class="relative h-90rpx w-90rpx flex justify-center justify-items-center rounded-100% bg-hex-e1eedf">
                  <image
                    :src="hot.productImage"
                    mode="scaleToFill"
                    class="h-90rpx w-90rpx rounded-100%"
                  />
                </div>
                <div class="ml-20rpx flex-1">
                  <span>
                    <span class="text-28rpx font-600 leading-38rpx">{{ hot.productName }}</span>
                    <span v-if="hot.isTop===1" class="ml-14rpx h24rpx w-38rpx rounded-br-12rpx rounded-tl-12rpx bg-hex-f3765a pb-2rpx pl-8rpx pr-8rpx text-20rpx font-300 text-hex-ffffff">Top</span>
                  </span>
                  <div class="flex">
                    <span class="flex-1 text-24rpx leading-28rpx text-hex-e36043">￥{{ hot.productPrice }}</span>
                    <div class="mr-32rpx"><uni-icons type="plus-filled" size="28" @click.stop="add(hot)" /></div>
                  </div>
                </div>
              </div>
              <div class="h-30rpx" />
            </div>
          </swiper-item>
        </swiper>
      </div>
    </div>
    <div><confirm ref="confirmRef" /></div>
  </div>
</template>

<script lang="ts" setup>
import { useSearchStore } from '../stores/history'

let searchStore: any = useSearchStore()
let confirmRef: any = $ref('')
//搜索关键字
let searchValue = $ref('')
//本地存储搜索历史数据
let searchHistory = uni.getStorageSync('searchHistory')
// let historyList: any[] = $ref(searchHistory ? JSON.parse(searchHistory) : [])
let historyList: any = $ref([])
onLoad(() => {
  historyList = searchStore.teaSearchHistoryList
})
//热门推荐
let hotSearchList: any[] = $ref([])
//获取热门推荐
const getHotSearch = async () => {
  const { data, error, status } = await Fetch('/qqyapi/product/product/hot/list', {
    method: 'get',
    headers: {
      AppType: 2,
    },
  })
  if (status === 200 && data.code === 0) {
    hotSearchList = data.result
  }
}
let hotShopList: any[] = $ref([])
//获取热门榜单
const hotShop = async () => {
  const { data, error, status } = await Fetch('/qqyapi/product/product/recommend/list', {
    method: 'get',
    headers: {
      AppType: 2,
    },
  })
  if (status === 200 && data.code === 0) {
    hotShopList = data.result
  }
}
//取消搜索
const cancelSearch = () => goback()
//搜索
const onSearch = (e) => {
  if (e.value.trim() === '') {
    return
  }
  //增加历史记录
  historyList.unshift(e.value)
  //去重
  let uniqueArr = [...new Set(historyList)]
  historyList = uniqueArr
  //给本地赋值
  // uni.setStorageSync('searchHistory', JSON.stringify(uniqueArr))
  searchStore.updateteaSearchHistoryList(historyList)
  navTo(`/pages-tea/searchResult?q=${searchValue}`)
  searchValue = '' // 清空搜索框
}
//返回上一级
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}

const goDetail = (type, id) => {
  if (type === 1) {
    navTo(`/pages-tea/doubleDetails?productId=${id}`)
  } else {
    navTo(`/pages-tea/details?productId=${id}`)
  }
}
let currentIndex = $ref(0)
let items: any = $ref([{
  label: '夏日热卖榜',
  data: [{
    id: 1,
    imageUrl: `${cdnUrl}/imgs/square/test1.png${imgVersion}`,
    price: 15,
    name: '茶一',
  }, {
    id: 2,
    imageUrl: `${cdnUrl}/imgs/square/test1.png${imgVersion}`,
    price: 15,
    name: '茶二',
  }, {
    id: 3,
    imageUrl: `${cdnUrl}/imgs/square/test1.png${imgVersion}`,
    price: 15,
    name: '茶二',
  }, {
    id: 4,
    imageUrl: `${cdnUrl}/imgs/square/test1.png${imgVersion}`,
    price: 15,
    name: '茶三',
  }],
}, {
  label: '冬季热卖榜',
  data: [{
    id: 1,
    imageUrl: `${cdnUrl}/imgs/square/test1.png${imgVersion}`,
    price: 15,
    name: '名称',
  }],
}])
const swiperChange = (e) => {
  currentIndex = e.detail.current
}
//添加购物车
const add = (item: any) => { }
//刷新事件
const heldeRefresh = () => getHotSearch()
//删除历史记录
const delHistory = () => {
  confirmRef.showConfirm('确定清空历史记录吗？').then(res => {
    if (res) {
      historyList = []
      searchStore.updateteaSearchHistoryList([])
      // uni.removeStorageSync('searchHistory')
    }
  })
}
//点击搜索历史
const heldHistory = (val) => {
  searchValue = val
  onSearch({ value: val })
}
let topHight = $ref(0)
onMounted(() => {
  getHotSearch()
  hotShop()
  // #ifdef MP-WEIXIN
  const { capsuleTop } = useCapsulePosition()
  topHight = capsuleTop.value
  // #endif
})
</script>

<style lang="scss">
.search{
  /* uni搜索组件样式修改 */
  .uni-searchbar{
    padding: 0;

    ::v-deep .uni-searchbar__cancel{
      color: #999 !important;
    }
  }

  .swiper-container{
    .item{
      overflow-y: auto;

      ::v-deep .uni-icons{
        color: #18a786 !important;
      }
    }
  }

}
</style>

